package com.example.week04_work2;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author nhsoft.ll
 */
public class AwaitDemo {


    public static void main(String[] args) throws Exception {

        Lock lock = new ReentrantLock();

        Condition condition = lock.newCondition();

        AwaitDemoSumTask sumTask = new AwaitDemoSumTask(lock, condition);

        long start = System.currentTimeMillis();
        sumTask.start();

        lock.lock();
        condition.await();
        lock.unlock();

        System.out.println("异步计算结果为：" + sumTask.getResult());
        System.out.println("使用时间：" + (System.currentTimeMillis() - start) + " ms");

    }
}

class AwaitDemoSumTask extends Thread {

    private Lock lock;

    private Condition condition;

    public AwaitDemoSumTask(Lock lock, Condition condition) {
        this.lock = lock;
        this.condition = condition;
    }

    private int result;

    public int getResult() {
        return result;
    }

    @Override
    public void run() {
        lock.lock();
        result = sum();
        System.out.println("线程运行结果:" + result);
        condition.signal();
        lock.unlock();

    }

    private int sum() {
        return fibo(36);
    }

    private int fibo(int a) {
        if (a < 2)
            return 1;
        return fibo(a - 1) + fibo(a - 2);
    }
}


